from datetime import datetime

from django.db.models import Prefetch
from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from Stage.models import Stage
from Stage.serializers import StageSerializers
from module.models import Module


# Create your views here.
class StageView(ModelViewSet):
    queryset = Stage.objects.all()
    serializer_class = StageSerializers

    # 分页
    pagination_class = PageNumberPagination
    PageNumberPagination.page_size_query_param = 'rows'

    # 查询阶段 接口
    def list(self, request, *args, **kwargs):
        # # 查询所有没有被删除的阶段1
        # queryset = self.get_queryset().filter(is_delete=False)
        #
        # # 进行分页
        # paginate = self.paginate_queryset(queryset)
        #
        # if paginate is None:
        #     return Response(data={"message": "该请求必须进行分页操作"}, status=status.HTTP_400_BAD_REQUEST)
        #
        # # 对分页后的结果进行序列化
        # serializer = self.get_serializer(paginate, many=True)
        # # 返回分页后的结果
        # return self.get_paginated_response(serializer.data)
        # 创建一个过滤后的 Module queryset，只获取未删除的模块
        modules_queryset = Module.objects.filter(is_delete=False)
        # 过滤 Stage 数据，确保只返回未删除的 Stage
        queryset = self.get_queryset().filter(is_delete=False)
        # 使用 Prefetch 来定制 Module 的查询，确保模块是未删除的
        queryset = queryset.prefetch_related(
            Prefetch('module_set', queryset=modules_queryset, to_attr='modules')
        )
        self.queryset = queryset
        return super().list(request, *args, **kwargs)


    def create(self, request, *args, **kwargs):
        # 查询阶段名是否已添加
        queryset = self.get_queryset().filter(name=request.data.get('name'), is_delete=False)
        if queryset:
            return Response(data={"message": "阶段名已存在"}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    @action(methods=["DELETE"], detail=False, url_path="batch", name="batch")
    def batch_remove(self, request, *args, **kwargs):
        # 批量删除
        self.get_queryset().filter(pk__in=request.data).update(delete_time=datetime.now(), is_delete=True)
        return Response(status=status.HTTP_204_NO_CONTENT) # 删除成功返回状态码

    def destroy(self, request, *args, **kwargs):
        # 删除阶段
        url = request.path
        id = url.rsplit("/")[-1]
        queryset = self.get_queryset().filter(id=id)
        if queryset:
            queryset.update(is_delete=True, update_time=datetime.now())
            return Response(data={"message": "删除成功"}, status=status.HTTP_200_OK)
        return Response(data={"message": "删除失败"}, status=status.HTTP_400_BAD_REQUEST)

    # 在修改阶段中,要首先查询到要修改的阶段内容
    @action(methods=['GET'], detail=False, url_path='edit-stage', url_name='edit-stage')
    def get_edit_stage(self, request, *args, **kwargs):
        # 根据id查询数据
        # 正确获取GET请求的查询参数
        ids = request.query_params.get('id')
        if ids is not None:
            queryset = self.get_queryset().filter(id=ids, is_delete=False)
            serializer = self.get_serializer_class()(queryset, many=True)  # 注意使用many=True来序列化查询集
            if serializer.data:  # 检查序列化后的数据是否为空
                return Response(data=serializer.data, status=status.HTTP_200_OK)
            else:
                return Response(status=status.HTTP_404_NOT_FOUND)  # 如果没有找到对应的记录，返回404状态码
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)  # 如果没有提供id参数，返回400状态码

    # 修改阶段名字
    @action(methods=['POST'], detail=False, url_name='update-stage', url_path='update-stage')
    def UpdateStage(self, request, *args, **kwargs):
        queryset = self.get_queryset().get(id=request.data['id'], is_delete=False)
        serializer = self.get_serializer(instance=queryset, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.instance.update_time = datetime.now()  # 手动设置更新时间
        serializer.save()
        if serializer.data:
            return Response(data=serializer.data, status=status.HTTP_200_OK)
        return Response(status=status.HTTP_404_NOT_FOUND)  # 如果没有找到对应的记录，返回404状态码
    # 重写查询所有的方法
    @action(methods=['GET'], detail=False, url_path='stageable', url_name='stageable')
    def stageable(self, request, *args, **kwargs):
        # 创建一个过滤后的 Module queryset，只获取未删除的模块
        modules_queryset = Module.objects.filter(is_delete=False)
        # 过滤 Stage 数据，确保只返回未删除的 Stage
        queryset = self.get_queryset().filter(is_delete=False)
        # 使用 Prefetch 来定制 Module 的查询，确保模块是未删除的
        queryset = queryset.prefetch_related(
            Prefetch('module', queryset=modules_queryset, to_attr='modules')
        )
        self.queryset = queryset
        serializer = StageSerializers(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
        # # 查询所有可用的阶段
        # queryset = self.get_queryset().filter(is_delete=False)
        # # 序列化满足条件的数据
        # serialize = self.get_serializer(queryset, many=True)
        # return Response(data=serialize.data, status=status.HTTP_200_OK)